<!DOCTYPE html>
<html lang="en" xmlns:class="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>我的购物车</title>
</head>
<style>
    .top-title:hover {
        cursor: pointer;
        color: #b31e22 !important;
    }
    .SearchBar input {
        height: 50px;
        width: 500px;
    }
    .menuList{
        background-color: #efd0d0 !important;
        color: #FFFFFF!important;
        height: 50px;
        line-height: 50px;
        text-align: center;
    }
    sapn{
        width: 100% !important;
        float: left !important;
        overflow: hidden !important;
        text-overflow: ellipsis !important;
        white-space: normal !important;
    }

</style>
<body>
<div id="app">
    <!--顶部用户导航栏-->
    <template>
        <div style="font-size: 14px;">
            <div style="display: flex;height: 60px;padding: 0 320px;background-color: #f5f5f5;border-radius: 10px">
                <div v-show="visibleAlready" style="margin-top: 3px">
                    <el-col :span="6">
                        <el-avatar style="height: 50px;width:50px;" :src="User.userImg"></el-avatar>
                    </el-col>
                    <el-col :span="18" style="line-height:50px">
                        <span style="padding-right: 30px;line-height: 40px;color: #666;margin-left:30px">{{User.realName}}</span>
                    </el-col>
                </div>
                <div v-show="visibleNotYet" style="margin-top: 10px">
                    <span style="padding-right: 20px;line-height: 40px;color: #666;">欢迎光临淘书网,请</span>
                    <el-button type="text" style="color: #666;margin-right: 10px;" class="top-title" @click="jumpLogin">登录</el-button>
                    <span style="padding-right: 20px;line-height: 40px;">|</span>
                    <el-button type="text" style="color: #666" class="top-title" @click="jumpRegister">注册</el-button>
                </div>
                <div style="flex: 1;display: flex;">
                    <div style="flex: 0.75;"></div>
                    <div style="width: 300px;display: flex;">
                        <el-button type="text" style="color: #666;margin-right: 10px;" class="top-title" @click="jumpPersonalCenter"> <i class="el-icon-user"></i>个人中心</el-button>
                        <el-button type="text" style="color: #666;margin-right: 10px;" class="top-title" @click="jumpCart"><i class="el-icon-shopping-cart-2"></i>购物车</el-button>
                        <el-button type="text" style="color: #666;margin-right: 10px;" class="top-title" @click="jumpOrders"><i class="el-icon-goods"></i>我的订单</el-button>
                        <el-button type="text" style="color: #666;margin-right: 10px;" class="top-title" @click="jumpCollect"><i class="el-icon-star-off"></i>我的收藏</el-button>
                        <el-button type="text" v-show="visibleAlready" style="color: #666;margin-right: 10px;" class="top-title" @click=" killSession"><i class="el-icon-switch-button"></i>退出登录</el-button>
                    </div>
                </div>
            </div>
        </div>
    </template>
    <div style="padding: 0 200px;">
        <div style="height: 50px;background-color: #B3C0D1;display: flex; align-items: center;">
            <el-link :underline="false" type="primary" href="/index.html"><span
                    style="color: white;font-size: 20px;margin-left: 20px;"><icon class="el-icon-s-home"></icon> 返回首页</span>
            </el-link>
        </div>
    </div>
    <template>
        <div style="padding: 0 210px">
            <div style="margin-top: 30px">
            <el-row>
                <el-form ref="searchForm" :inline="true" :model="searchDialog" >
                    <el-row>
                        <el-col :span="6">
                            <el-form-item label="书名：">
                                <el-input style="width:180px " v-model="searchDialog.bookName" placeholder="Name"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-form-item label="加购时间：">
                        <el-col  :span="8">
                            <el-date-picker type="date" placeholder="最远日期" v-model="searchDialog.startDate" style="width: 100%;"></el-date-picker>
                        </el-col>
                            <el-col class="line" align="center"style="font-size: 20px" :span="2">-</el-col>
                        <el-col :span="8">
                            <el-date-picker placeholder="最近日期" v-model="searchDialog.endDate" style="width: 100%;"></el-date-picker>
                        </el-col>
                        </el-form-item>
                        <el-form-item>
                            <el-row style="margin-left: -100px">
                            <el-button type="primary" icon="el-icon-search" @click="onSubmit">搜索</el-button>
                            <el-button type="success" icon="el-icon-refresh" @click="resetSearch">重置</el-button>
                            <el-button type="danger" @click="deleteByIds">批量删除</el-button>
                            </el-row>
                        </el-form-item>
                    </el-row>
                </el-form>

            </el-row>
            </div>
            <el-table
                    :data="tableData"
                    :row-key="getRowKey"
                    border stripe size="medium"
                    @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55px" align="center" :selectable="checkSelectable" :reserve-selection="true"></el-table-column>
                <el-table-column prop="bookImg" label="书本封面" align="center">
                    <template v-slot="scope">
                    <el-image style="width: 100px;height: 110px" :src="scope.row.bookImg"></el-image>
                    </template>
                </el-table-column>
                <el-table-column prop="bookName" label="书名" align="center"></el-table-column>
                <el-table-column prop="bookPrice" label="单价" width="100px" align="center">
                    <template v-slot="scope">
                        <span style="color:orangered">￥{{scope.row.bookPrice}}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="quantity" label="数量" align="center">
                    <template v-slot="scope">
                      <el-input-number v-model="scope.row.quantity" :min="1" :max="scope.row.inventory" @change="updateQuantity(scope)"></el-input-number>
                    </template>
                </el-table-column>
                <el-table-column prop="addTime" label="加购时间" align="center" ></el-table-column>
                <el-table-column
                        align="center"
                        width="100px"
                        label="操作"
                        >
                    <template slot-scope="scope">
                        <el-button type="danger" icon="el-icon-delete" circle @click="deleteById(scope.row)"></el-button><!--删除-->
                    </template>
                </el-table-column>
            </el-table>
            <el-dialog
                    title="结算中"
                    :visible.sync="popShow"
                    width="25%"
                    :before-close="handleClose">
                <el-row><span style="font-size: 17px;margin-left: 20px"><span style="color: red">{{count}}秒</span>后前往订单详情页</span></el-row>
                <el-row>
                    <br><el-button @click="jumpCart" style="margin-left: 200px">点击取消</el-button>
                </el-row>
            </el-dialog>
            <br>
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="currentPage"
                    :page-sizes="[5, 10, 15, 20]"
                    :page-size="5"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="totalCount">
            </el-pagination>
            <div style="margin: 10px 0;text-align: right">
                <span style="font-size: 20px;">总价：<span style="color:orangered">{{totalPrice.toFixed(2)}}</span></span><br><br>
                <el-button style="color: #FFFFFF;background-color: orangered;font-size: 20px" size="medium" @click="settleAccounts">结算</el-button>
            </div>
        </div>
    </template>
</div>
</body>
<!-- 引入组件库 -->
<script src="../js/vue.js"></script>
<script src="../element-ui/lib/index.js"></script>
<link rel="stylesheet" href="../element-ui/lib/theme-chalk/index.css">
<script src="../js/axios-0.18.0.js"></script>
<script src="../js/request.js"></script>
<<script>
    new Vue({
        el: '#app',
        created() {
            //钩子函数，vue对象初始化后执行
            this.getUser();
        },
        mounted() {
            this.showCart();

        },
        methods: {
            //显示所有购物项
            showCart(){
                var _this=this;
                axios({
                    method:"post",
                    url:"/cart/page?currentPage="
                    + this.currentPage + "&pageSize=" + this.pageSize,
                    data:_this.searchDialog
                }).then(resp =>{
                    _this.tableData = resp.data.items;
                    //设置表格总记录数
                    _this.totalCount = resp.data.totalCount;
                })
            },
            //修改购物项数量
            updateQuantity(scope){
                let quantity=scope.row.quantity
                let id=scope.row.id
                axios({
                    method:"get",
                    url:"/cart/quantity?quantity="
                        +quantity+"&id="+id,
                }).then(resp =>{
                    this.totalPrice=0;
                    this.showCart();
                    // this.multipleSelection.
                    this.multipleSelection.forEach(item=>{
                        if (item.id==id){
                            item.quantity=quantity
                        }
                        this.totalPrice+=item.quantity * item.bookPrice;//更新选中金额
                    })
                })
            },
            //结算
            settleAccounts(){
                if (!this.multipleSelection || !this.multipleSelection.length ){
                    this.$message.error("请选择需要结算的书籍");
                    return;
                }
                let data={
                    name:this.multipleSelection[0].bookName,
                    bookImg:this.multipleSelection[0].bookImg,
                    totalPrice:this.totalPrice,
                    carts:this.multipleSelection
                }
                console.log(data);
                axios({
                    method:"post",
                    url:"/orders/create?type=cart",
                    data:data
                }).then(resp =>{
                    if (resp.data.code==1){//结算成功
                        console.log(resp.data)
                        // 重新查询数据
                        this.popShow = true
                        const TIME_COUNT = 3;
                        if(!this.timer){
                            this.count = TIME_COUNT;
                            this.popShow = true;
                            this.timer = setInterval(()=>{
                                if(this.count > 0 && this.count <= TIME_COUNT){
                                    this.count--;
                                }else{
                                    this.popShow = false;
                                    clearInterval(this.timer);
                                    this.timer = null;
                                    this.showCart();
                                    console.log(resp.data)
                                    this.jumpConfirmAddress(resp.data.data);
                                }
                            },1000)
                        }
                    }else{
                        this.$message.error("商品库存不足,请重新下单")
                        this.showCart();
                    }
                })
            },
            handleSelectionChange(val){
                this.totalPrice=0;
                this.multipleSelection=val;
                console.log(this.multipleSelection);
                val.forEach(item=> {
                    if (val && val.length) {
                        console.log(item.quantity)
                        console.log(item.bookPrice)
                        this.totalPrice += item.quantity * item.bookPrice;
                    }
                })
            },
            handleSizeChange(val) {
                this.pageSize = val;
                this.showCart();
                // console.log(`每页 ${val} 条`);
            },
            //当前页数
            handleCurrentChange(val) {
                this.currentPage = val;
                this.showCart();
                // console.log(`当前页: ${val}`);
            },
            deleteById(row){

                this.$confirm('确认是否从购物车移除该书?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    var _this = this;
                    axios({
                        method: "delete",
                        url: "/cart",
                        data:[row.id]
                    }).then(function (resp) {
                        if (resp.data.code == 1) {//删除成功
                            // 重新查询数据
                            _this.showCart();

                            _this.$message({
                                type: 'success',
                                message: '删除成功!'
                            });
                        }
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            deleteByIds() {
                console.log(this.multipleSelection)
                //获取选择的id数组
                for(let i=0;i<this.multipleSelection.length;i++){
                    let selectionElement=this.multipleSelection[i];
                    this.selectIds[i]=selectionElement.id
                }

                this.$confirm('确认是否从购物车移除所选书本,?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    var _this = this;

                    axios({
                        method: "delete",
                        url: "/cart",
                        data:_this.selectIds
                    }).then(function (resp) {
                        if (resp.data.code == 1) {//删除成功
                            // 重新分页数据
                            _this.showCart();

                            _this.$message({
                                type: 'success',
                                message: '删除成功!'
                            });
                        }
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            onSubmit() {
                this.currentPage = 1;//每次查询回到页码到第一页
                this.showCart();
            },
            resetSearch() {
                this.searchDialog = {
                    bookName: undefined,
                }
                this.showCart();
            },
            getRowKey(row) {
                return row.id;
            },
            getUser() {//获取用户名
                //发送ajax请求
                axios({
                    method:"get",
                    url:"/user",
                }).then(resp =>{
                    this.User = resp.data;
                    if (this.User !== null && this.User !== ""&& this.User !==undefined) {
                        this.visibleNotYet = false;
                        this.visibleAlready= true;
                    }else{this.User={username:null}}
                })
            },
            killSession() {//退出登录
                this.$confirm('确认退出登录, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.visibleNotYet = true;
                    this.visibleAlready = false;
                    //发送ajax请求
                    axios.post("/user/logout").then((res) => {

                    })
                    window.location.href = "../index.html"
                    this.$message({
                        message: '退出成功',
                        type: 'success'
                    });
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消'
                    });
                });
            },
            //商品下架或库存小于数量时不可选
            checkSelectable(row) {
                if (row.status == '-1'||row.inventory<row.quantity){
                    return false;
                }
                return true;
            },
            handleSelect(key, keyPath) {
                console.log(key, keyPath);
            },
            handleClose(key, keyPath) {
                this.$refs.menus.open(keyPath);
            },
            jumpConfirmAddress(ordersId){
                window.location.href = "confirmAddress.html?ordersId=" + ordersId;
            },
            jumpAllBook(){
                location.href ="/user_page/allBook.html";
            },
            jumpIndex(){
                location.href ="/index.html";
            },
            jumpLogin(){
                location.href ="/login_page/login.html";
            },
            jumpRegister(){
                location.href ="/login_page/register.html";
            },
            jumpPersonalCenter(){
                location.href ="/user_page/personCenter.html";
            },
            jumpCollect(){
                location.href ="/user_page/collect.html";
            },
            jumpCart(){
                location.href ="/user_page/cart.html";
            },
            jumpOrders(){
                location.href ="/user_page/orders.html";
            }
        },
        data() {
            return {
                User:[],//用户信息
                visibleNotYet:true,
                visibleAlready:false,
                pageSize:5,
                totalCount:100,
                currentPage:1,
                selectIds:[],
                multipleSelection:[],
                //已选总价
                totalPrice:0,
                tableData:[],//购物项数据
                cart:{ quantity:1 },
                popShow: false,
                count:'',//倒计时
                searchDialog:{

                },
                book:{
                    id:'',
                    bookName:'',
                    author:'',
                    bookImg:'',
                    bookPrice:'',
                    inventory:'',
                    introduction:'',
                    addTime:''
                },
            }
        }
    })
</script>
</html>